<template>
    <div @selectstart.prevent @mousedown.prevent>
        <a-float-button type="primary" :style="{ right: '24px' }">
            <template #icon>
                <CloudUploadOutlined />
            </template>
        </a-float-button>

        <div class="file-browser-container">
            <!-- Scrollable content area -->
            <div class="scrollable-content">
                <a-dropdown :trigger="['contextmenu']">
                    <div>
                        <!-- 图标视图 -->
                        <a-list v-if="viewMode === 'IconView'" :data-source="filteredFiles"
                            :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 6, xxl: 8 }">
                            <template #renderItem="{ item }">
                                <a-list-item>
                                    <a-dropdown :trigger="['contextmenu']">
                                        <div @contextmenu.stop>
                                            <div class="file-item" :data-id="item.id"
                                                :class="{ 'file-item-selected': selectedFiles.includes(item.id) }"
                                                @click="handleFileClick(item, $event)">
                                                <div class="file-icon">
                                                    <img :src="getFileIcon(item.type)" :alt="item.type" />
                                                </div>
                                                <div class="file-info">
                                                    <div class="file-name">{{ item.name }}</div>
                                                </div>
                                            </div>
                                        </div>
                                        <template #overlay>
                                            <a-menu>
                                                <a-menu-item key="1">下载</a-menu-item>
                                                <a-menu-item key="2">重命名</a-menu-item>
                                                <a-menu-item key="3" @click="showFileProperties(item)">属性</a-menu-item>
                                                <a-menu-divider />
                                                <a-menu-item key="4">删除</a-menu-item>
                                            </a-menu>
                                        </template>
                                    </a-dropdown>
                                </a-list-item>
                            </template>
                        </a-list>

                        <!-- 表格视图 -->
                        <template v-else>
                            <a-table :dataSource="filteredFiles" :columns="columns" :rowKey="record => record.id"
                                :bordered="false" :pagination="false"
                                :customRow="() => ({ style: { cursor: 'pointer' } })"
                                :scroll="{ y: 'calc(100vh - 200px)' }"
                                @change="(pagination, filters, sorter) => handleTableChange(pagination, filters, sorter)"
                                style="width: 100%;">
                                <!-- 自定义名称列渲染 -->
                                <template #bodyCell="{ column, record }">
                                    <div v-if="column.dataIndex === 'name'" class="table-file-item"
                                        :class="{ 'table-file-item-selected': selectedFiles.includes(record.id) }"
                                        @click.stop="handleFileClick(record, $event)">
                                        <div class="file-item-table-content">
                                            <div class="tablt-file-icon" style="display: flex; align-items: center;">
                                                <img :src="getFileIcon(record.type)" :alt="record.type" width="24"
                                                    height="24" class="table-view-icon" />
                                            </div>
                                            <div class="file-name-text">{{ record.name }}</div>
                                        </div>
                                    </div>
                                </template>
                            </a-table>
                        </template>
                    </div>

                    <!-- 网盘右键菜单保持不变 -->
                    <template #overlay>
                        <a-menu>
                            <a-menu-item key="1">刷新</a-menu-item>
                            <a-menu-item key="2" @click="handleUploadClick">上传文件</a-menu-item>
                            <input type="file" ref="fileInput" style="display: none" @change="handleFileChange"
                                multiple />
                        </a-menu>
                    </template>
                </a-dropdown>
            </div>
        </div>

        <!-- 文件属性弹窗 -->
        <a-modal v-model:open="visible" :title="currentFile?.name" @cancel="handleCancel" :footer="null" width="400px"
            class="file-properties-modal">
            <div class="file-properties-content" @selectstart.prevent @mousedown.prevent style="cursor: default;">
                <!-- 大图标 -->
                <div class="file-icon-wrapper">
                    <img :src="getFileIcon(currentFile?.type)" :alt="currentFile?.type" class="property-file-icon" />
                </div>

                <!-- 左对齐居中的属性列表 -->
                <div class="properties-list">
                    <div class="property-item">
                        <span class="property-label">类型：</span>
                        <span class="property-value">{{ currentFile?.type }}</span>
                    </div>
                    <div class="property-item">
                        <span class="property-label">大小：</span>
                        <span class="property-value">{{ formatFileSize(currentFile?.size) }}</span>
                    </div>
                    <div class="property-item">
                        <span class="property-label">位置：</span>
                        <span class="property-value">全部文件</span>
                    </div>
                    <div class="property-item">
                        <span class="property-label">创建时间：</span>
                        <span class="property-value">{{ formatDate(currentFile?.created_at) }}</span>
                    </div>
                    <div class="property-item">
                        <span class="property-label">修改时间：</span>
                        <span class="property-value">{{ formatDate(currentFile?.updated_at) }}</span>
                    </div>
                </div>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue';
import filesData from '@/assets/files.json';
import { CloudUploadOutlined } from '@ant-design/icons-vue';
import { Table } from 'ant-design-vue';

export default {
    components: {
        CloudUploadOutlined,
        ATable: Table
    },
    props: {
        category: {
            type: String,
            default: 'all'
        },
        viewMode: {
            type: String,
            default: 'IconView'
        }
    },
    setup (props) {
        // 文件类型分组
        const fileGroups = {
            document: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'],
            image: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg', 'ico', 'tiff', 'tif', 'heic', 'heif'],
            video: ['mp4', 'mkv', 'flv', 'avi', 'mov', 'wmv', 'mpeg', 'mpg', 'webm', '3gp', 'ts', 'mts', 'm2ts'],
            audio: ['mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a', 'wma', 'alac', 'ape', 'opus']
        };

        const columns = [
            {
                title: '文件名',
                dataIndex: 'name',
                key: 'name',
                scopedSlots: { customRender: 'name' }
            },
            {
                title: '类型',
                dataIndex: 'type',
                key: 'type'
            },
            {
                title: '大小',
                dataIndex: 'size',
                key: 'size',
                customRender: ({ text }) => formatFileSize(text)
            },
            {
                title: '修改时间',
                dataIndex: 'updated_at',
                key: 'updated_at',
                customRender: ({ text }) => formatDate(text)
            }
        ];

        const files = ref([]);
        const filteredFiles = computed(() => {
            const cat = props.category;

            if (cat === 'all') {
                return files.value;
            }

            return files.value.filter(file => {
                switch (cat) {
                    case 'document':
                        const ext = file.name.split('.').pop();
                        return fileGroups.document.includes(ext);
                    case 'image':
                        return file.type === 'image' || file.type === 'ico';
                    case 'video':
                        return file.type === 'video';
                    case 'audio':
                        return file.type === 'audio';
                    case 'other':
                        const extOther = file.name.split('.').pop();
                        return !fileGroups.document.includes(extOther) &&
                            !['image', 'ico', 'video', 'audio'].includes(file.type);
                    default:
                        return true;
                }
            });
        });

        watch(
            () => props.category,
            (newCat) => {
                console.log('Category changed to:', newCat);
            }
        );

        const visible = ref(false);
        const currentFile = ref(null);
        const fileInput = ref(null);
        const selectedFiles = ref([]);

        // 点击上传文件
        const handleUploadClick = () => {
            fileInput.value.click();
        };

        // 文件选择处理
        const handleFileChange = (event) => {
            const uploadedFiles = event.target.files;
            if (uploadedFiles.length > 0) {
                console.log('选择的文件:', uploadedFiles);
            }
            event.target.value = '';
        };

        // 处理文件点击
        const handleFileClick = (file, event) => {
            const isCtrlPressed = event.ctrlKey || event.metaKey;
            const fileId = file.id;
            const index = selectedFiles.value.indexOf(fileId);

            if (isCtrlPressed) {
                if (index > -1) {
                    selectedFiles.value.splice(index, 1);
                } else {
                    selectedFiles.value.push(fileId);
                }
            } else {
                selectedFiles.value = [fileId];
            }
        };

        // 获取图标路径
        const fileTypeToIcon = {
            document: 'Word',
            spreadsheet: 'Excel',
            presentation: 'PPT',
            image: '图片',
            pdf: 'Pdf',
            database: '数据库',
            video: '视频',
            archive: '压缩包',
            config: '配置文件',
            design: '未知文件',
            audio: '音频',
            log: 'Txt',
            notebook: 'Txt',
            web: '链接',
            disk: '3D',
            font: '未知文件',
            markdown: 'Txt',
            script: '程序',
            diagram: '配置文件'
        };

        const getFileIcon = (fileType) => {
            const iconName = fileTypeToIcon[fileType] || '未知文件';
            return new URL(`/src/assets/icons/文件类型-${iconName}.svg`, import.meta.url).href;
        };

        // 格式化大小
        const formatFileSize = (bytes) => {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        };

        // 格式化日期
        const formatDate = (dateString) => {
            const date = new Date(dateString);
            return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
        };

        // 显示属性弹窗
        const showFileProperties = (file) => {
            currentFile.value = file;
            visible.value = true;
        };

        const handleCancel = () => {
            visible.value = false;
        };

        // 点击空白区域取消选择
        const handleDocumentClick = (event) => {
            const target = event.target;
            if (!target.closest('.file-item')) {
                selectedFiles.value = [];
            }
        };

        onMounted(() => {
            files.value = filesData.files;
            document.addEventListener('click', handleDocumentClick);
        });

        return {
            files,
            visible,
            currentFile,
            selectedFiles,
            showFileProperties,
            handleCancel,
            getFileIcon,
            formatFileSize,
            formatDate,
            handleUploadClick,
            handleFileClick,
            fileInput,
            filteredFiles,
            CloudUploadOutlined,
            handleFileChange,
            columns
        };
    }
};
</script>

<style>
::v-deep .ant-table table td {
    padding-top: 2px;
    padding-bottom: 2px;
}

.table-file-item {
    display: flex;
    align-items: center;
    padding: 4px 8px;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.table-file-item:hover {
    background-color: #f5f5f5;
}

.table-file-item-selected {
    background-color: #e6f7ff;
    border-color: #1890ff;
}

.table-file-item,
.table-file-item * {
    transition: none !important;
    transform: none !important;
    box-shadow: none !important;
    filter: none !important;
}

.file-item-table-content {
    display: flex;
    align-items: center;
    gap: 12px;
    width: 100%;
}

.file-item-table-content .file-name-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;
}

.file-item-table .file-icon img.table-view-icon {
    width: 16px;
    height: 16px;
    transition: none !important;
    filter: none !important;
    transform: scale(1) !important;
}

.file-item-table:hover {
    background-color: transparent !important;
}

.file-item-table.file-item-selected {
    background-color: #e6f7ff !important;
    border-color: #1890ff !important;
}

.file-browser-container {
    display: flex;
    flex-direction: column;
    height: 100%;
}

::v-deep .ant-table {
    font-size: 14px;
    width: 100%;
}

::v-deep .ant-table table {
    line-height: 1.2;
}

::v-deep .ant-table table td {
    padding-top: 4px;
    padding-bottom: 4px;
}

.scrollable-content {
    flex: 1;
    overflow-y: auto;
    position: relative;
}

.file-item {
    padding: 12px 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    border: 2px solid transparent;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    background: #ffffff;
    position: relative;
    overflow: hidden;
    user-select: none;
}

.file-item:hover {
    border-color: #d9d9d9;
    background: linear-gradient(135deg, #fafafa 0%, #f5f5f5 100%);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08), 0 2px 4px rgba(0, 0, 0, 0.05);
    transform: translateY(-1px);
}

.file-item:hover .file-icon img {
    transform: scale(1.05);
    filter: brightness(1.1);
}

.file-item-selected {
    border-color: #1890ff !important;
    background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%) !important;
    box-shadow:
        0 0 0 2px rgba(24, 144, 255, 0.2),
        0 4px 16px rgba(24, 144, 255, 0.15),
        0 2px 6px rgba(24, 144, 255, 0.1) !important;
    transform: translateY(-2px) !important;
}

.file-item-selected::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(24, 144, 255, 0.05) 0%, rgba(24, 144, 255, 0.02) 100%);
    border-radius: inherit;
    pointer-events: none;
}

.file-item-selected .file-name {
    color: #1890ff;
    font-weight: 600;
}

.file-item-selected .file-icon img {
    transform: scale(1.08);
    filter: brightness(1.15) saturate(1.2);
}

.file-icon img {
    width: 64px;
    height: 64px;
    margin-bottom: 12px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.file-info {
    width: 100%;
    z-index: 1;
    position: relative;
}

.file-name {
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 4px;
    transition: color 0.3s ease;
    color: #333;
}

.file-size,
.file-date {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);
    transition: color 0.3s ease;
}

.file-date {
    margin-top: 2px;
}

.file-item:active {
    transform: translateY(0px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.08);
}

.file-item-selected:active {
    transform: translateY(-1px);
    box-shadow:
        0 0 0 2px rgba(24, 144, 255, 0.3),
        0 2px 12px rgba(24, 144, 255, 0.2),
        0 1px 4px rgba(24, 144, 255, 0.15);
}

/* 模态框样式 */
.file-properties-modal :deep(.ant-modal-body) {
    padding: 20px;
}

.file-properties-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
}

.file-icon-wrapper {
    text-align: center;
    margin: 10px 0;
}

.property-file-icon {
    object-fit: contain;
    filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.5));
    border-radius: 8px;
    width: 80px;
    height: 80px;
}

.properties-list {
    width: 80%;
    margin: 0 auto;
}

.property-item {
    display: flex;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
}

.property-label {
    font-weight: 500;
    color: #666;
    width: 100px;
    text-align: left;
}

.property-value {
    color: #333;
    flex: 1;
    text-align: left;
    padding-left: 12px;
}
</style>